<?php

class CategoryModel extends Model {
	public $table = 'category';
	private $ThumbStr;

	public function getCategory(){
		return $this->order('cid ASC')->select();
	}

	public function editCategory($cid){
		if(empty($cid)){
			$this->error = '非法操作!!';
		}
		return $this->where("cid = $cid")->update($_POST);
	}

	public function deleteCategory($cid){
		if(empty($cid)){
			$this->error = '非法操作';
			return false;
		}
		$Sql = "SELECT b.bid , thumb FROM blog AS b JOIN category AS cat ON b.cid = cat.cid WHERE cat.cid = $cid";
		$resNum = $this->query($Sql);
		// 博文id
		$BidArr = array();
		// 图片路径
		$ThumbArr = array();
		// 博文id
		foreach ($resNum as $key => $val) {
			$BidArr[] = current($val);
			next($val);
		}
		// 图片路径
		foreach ($resNum as $key => $val) {
			next($val);
			$ThumbArr[] = current($val);
		}
		// 博文id字符串
		$BlogNum = implode(',', $BidArr);
		// 图片路径字符串
		$ThumbStr = implode(',', $ThumbArr);
		$this->ThumbStr = $ThumbStr;
		// echo $ThumbNum;exit;
		// echo $BlogNum;exit;
		$DeleteCat = "DELETE FROM category WHERE cid IN($cid)";
		$DeleteBlog = "DELETE FROM blog WHERE bid IN($BlogNum)";
		if($this->exe($DeleteCat)){
			if($this->exe($DeleteBlog)){
				$this->UnThumb();
				return true;
			}else{
				$this->error('删除博文时出现错误  | '.mysql_error());
				return false;
			}
		}else{
			$this->error('删除分类时出现错误  | '.mysql_error());
			return false;
		}
	}

	public function UnThumb(){
		$Thumb = explode(',', $this->ThumbStr);
		foreach ($Thumb as  $Files) {
			if(is_file($Files)){
				unlink($Files);
			}
		}
		return true;
	}

	public function AddCat(){
		$field = $this->where("catname = '{$_POST['catname']}'")->find();
		if($field){
			$this->error = '此分类已存在';
			return false;
		}
		return $this->insert($_POST);
	}
}

?>